<script setup>
import Edit from './components/Edit.vue'
import axios from 'axios'
import {ref, onMounted } from 'vue'

// TODO: 列表渲染
// const tableData = ref([
//   { id: 1, name: 'Jack', place: 'New York' },
//   { id: 2, name: 'Tom', place: 'Los Angeles' },
//   { id: 3, name: 'Alice', place: 'Chicago' }
// ]);
const tableData = ref([]);
const fetchList = async () => {
  try {
    const response = await axios.get('/list');
    tableData.value = response.data;
  } catch (error) {
    console.error('获取列表失败', error);
  }
};

// TODO: 删除功能
const deleteItem = async (row) => {
  try {
    await axios.delete(`/del/${row.id}`);
    fetchList();  // 删除成功后刷新列表
  } catch (error) {
    console.error('删除失败', error);
  }
};



// TODO: 编辑功能
const isEditVisible = ref(false);
const currentItem = ref(null);

const editItem = (row) => {
  currentItem.value = { ...row };
  isEditVisible.value = true;
};

const updateItem = async (item) => {
  try {
    await axios.patch(`/edit/${item.id}`, {
      name: item.name,
      place: item.place
    });
    isEditVisible.value = false;
    fetchList();  // 编辑成功后刷新列表
  } catch (error) {
    console.error('编辑失败', error);
  }
};

// 在组件挂载时获取列表数据
onMounted(() => {
  fetchList();
});

</script>

<template>
  <div class="app">
    <el-table :data="tableData">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="姓名" prop="name" width="150"></el-table-column>
      <el-table-column label="籍贯" prop="place"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" link @click="editItem(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="deleteItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

    <!-- 传递编辑数据到 Edit 组件 -->
    <Edit v-if="isEditVisible" :item="currentItem" @save="updateItem" @close="isEditVisible = false" />
  <!-- <Edit /> -->
</template>

<style scoped>
.app {
  width: 980px;
  margin: 100px auto 0;
}
</style>
